package com.guodaxia.gzh.web;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ha")
public class SseController {

//    private final ExecutorService executorService = Executors.newCachedThreadPool();

    @GetMapping("/sse")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    for (int i = 0; i < 10; i++) {
                        emitter.send("Message " + i, MediaType.TEXT_PLAIN);
                        TimeUnit.SECONDS.sleep(1);
                    }
                    emitter.complete();
                } catch (IOException | InterruptedException e) {
                    emitter.completeWithError(e);
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return emitter;
    }
}
